package studio.banner.reference.config.interceptor;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.HandlerInterceptor;
import studio.banner.reference.entity.Document;
import studio.banner.reference.entity.UserInfo;
import studio.banner.reference.service.DocumentService;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class DocumentInterceptor implements HandlerInterceptor {
    private final String adminRole = "admin";
    private final String userIdStr = "userId";
    private final String documentIdStr = "documentId";
    @Autowired
    private DocumentService documentService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        Integer userId = (Integer) request.getSession().getAttribute(userIdStr);
        Integer documentId = Integer.parseInt(request.getParameter(documentIdStr));
        Document document = documentService.getById(documentId);
        UserInfo userInfo = new UserInfo();
        return userId != null && document != null
                && (userInfo.getRole().equals(adminRole) || document.getUserId().equals(userId));
    }
}
